const fs        = require('fs');
const nodeSchedule  = require('node-schedule');
const config = require("../db/config");
const log4js     = require('../utils/logUtils');
const logger     = log4js.getLogger('service');

const TAG = "[计划任务] [清理日志]";
let mySchedule;

/**
 * 计划任务，检查磁盘空间是否满了
 */
let FreeLogs={
    /**
     * 开启定时器
     */
    start:function(){
        const interval= '30 1 * * * *';
        const that = this;
        logger.info(TAG, '启动计划任务', interval);
        mySchedule = nodeSchedule.scheduleJob(interval,async function(){
            let path = config.logger.path;
            await that.checkLog(path,config.logger.filecount,/^(.*)request(.*)\.log(.*)$/ );
            await that.checkLog(path,config.logger.filecount,/^(.*)error(.*)\.log(.*)$/ );
            await that.checkLog(path,config.logger.filecount,/^(.*)info(.*)\.log(.*)$/ );
        });
    },
    /**
     * 取消定时器
     */
    stop:function(){
        if(mySchedule){
            mySchedule.cancel();
        }
    },
    /**
     * path 路径
     * count 留几个
     * pattern 文件名匹配正则表达式
     */
    checkLog(path,count,pattern){
        return new Promise((resolve,reject)=>{

            if(path.charAt(path.length-1)!=='/') path+='/';
            logger.info(TAG, '检查目录', path, pattern);
            fs.readdir(path,function(err){
                if(err){
                    logger.error(TAG, "读取文件错误", err);
                    reject(err);
                }else {
                    let files = fs.readdirSync(path)
                        .map(function (v) {
                            let stat = fs.statSync(path + v);
                            return {name: v, time: stat.ctime.getTime()};
                        })
                        .sort(function (a, b) {
                            return a.time - b.time;
                        })
                        .map(function (v) {
                            return v.name;
                        });

                    if (pattern) {
                        files = files.filter(x => pattern.test(x));
                    }

                    if (files.length > 5) {
                        for (let i = 0; i < files.length - 5; i++) {
                            let tmp = path + files[i];
                            fs.unlink(path + files[i], (err) => {
                                if (err) {
                                    logger.error(TAG, '出现错误', err);
                                    reject();
                                } else {
                                    logger.info(TAG, '删除成功', tmp);
                                    resolve();
                                }
                            });
                        }
                    }else{
                        resolve();
                    }
                }
            });
        });
    }
};

module.exports=FreeLogs;
